package com.ecp.commons.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

public abstract class AbstractExcludeUrlFilter extends HttpServlet implements Filter {

	private static final long	serialVersionUID	= 1L;
	protected FilterConfig		filterConfig;

	//Handle the passed-in FilterConfig
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public boolean doExclude(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String excludeUrls = this.getInitParameter("excludeUrls");
		String[] excludes = excludeUrls.split(";");

		HttpServletRequest httprequest = (HttpServletRequest) request;

		for (int i = 0; i < excludes.length; i++) {
			String path = httprequest.getServletPath();
			String regx = excludes[i].replaceAll("\\.", "\\\\.");
			regx = regx.replaceAll("\\*", "\\.*");
			if (excludes[i].endsWith("/")) {
				regx += ".*";
			}

			if (path.matches(regx)) {
				return true;
			}
		}
		return false;

	}

	public boolean doInclude(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String includeUrls = this.getInitParameter("includeUrls");
		String[] includes = includeUrls.split(";");

		HttpServletRequest httprequest = (HttpServletRequest) request;

		for (int i = 0; i < includes.length; i++) {
			String path = httprequest.getServletPath();
			String regx = includes[i].replaceAll("\\.", "\\\\.");
			regx = regx.replaceAll("\\*", "\\.*");
			if (includes[i].endsWith("/")) {
				regx += ".*";
			}

			if (path.matches(regx)) {
				return true;
			}
		}
		return false;
	}

	public String getInitParameter(String name) {
		return filterConfig.getInitParameter(name);
	}

	public Enumeration<?> getInitParameterNames() {
		return filterConfig.getInitParameterNames();
	}
}
